<template>
  <div class="exam-taking-container">
    <!-- 使用水平布局 -->
    <el-container direction="horizontal" v-if="!isLoading && examData" style="height: 100%;">
      
      <!-- 左侧主区域 -->
      <el-main class="main-panel">
        <el-container direction="vertical" style="height: 100%;">
          <el-header class="exam-header">
            <!-- 使用 Flex 布局优化 Header -->
            <div class="header-left">
              <span class="title">{{ examData.examTitle || examData.title || '在线考试' }}</span>
            </div>
            <div class="header-center">
               <span class="timer">剩余时间: {{ formattedTime }}</span>
            </div>
            <div class="header-right">
              <span class="progress">已答: {{ answeredQuestionsCount }} / {{ totalQuestions }}</span>
              <div class="suspicion-level" v-if="suspiciousInfo.suspicious_level > 0">
                 <el-tooltip effect="dark" :content="suspicionTooltipContent" placement="bottom">
                  <el-tag :type="suspicionTagType" size="small">
                    <el-icon><WarningFilled /></el-icon>
                    可疑等级: {{ suspiciousInfo.suspicious_level }}
                  </el-tag>
                </el-tooltip>
              </div>
            </div>
          </el-header>

          <el-main class="question-area">
            <!-- 题目内容区域 -->
            <div v-if="currentQuestion" class="question-content">
              <div class="question-stem">
                 <span class="q-index">{{ currentQuestionIndex + 1 }}.</span>
                 <span class="q-type">[{{ getQuestionTypeText(currentQuestion.type) }}]</span>
                 <span class="q-score">({{ currentQuestion.score }}分)</span>
                 <div class="stem-text" v-html="currentQuestion.content"></div>
              </div>
              <div class="answer-options">
                 <!-- 各类型题目的选项/输入框... 保持不变 -->
                 <el-radio-group v-if="currentQuestion.type === 'SINGLE_CHOICE'" v-model="currentAnswer" @change="handleAnswerChange">
                   <el-radio 
                     v-for="(option, index) in parseOptions(currentQuestion.options)" 
                     :key="index" 
                     :value="option.key"
                     class="option-item"
                    >
                     {{ option.key }}. {{ option.value }}
                   </el-radio>
                 </el-radio-group>
                 <el-checkbox-group v-else-if="currentQuestion.type === 'MULTIPLE_CHOICE'" v-model="currentAnswer" @change="handleAnswerChange">
                   <el-checkbox 
                     v-for="(option, index) in parseOptions(currentQuestion.options)" 
                     :key="index" 
                     :value="option.key"
                     class="option-item"
                    >
                     {{ option.key }}. {{ option.value }}
                   </el-checkbox>
                 </el-checkbox-group>
                 <el-radio-group v-else-if="currentQuestion.type === 'TRUE_FALSE'" v-model="currentAnswer" @change="handleAnswerChange">
                   <el-radio value="true" class="option-item">正确</el-radio>
                   <el-radio value="false" class="option-item">错误</el-radio>
                 </el-radio-group>
                 <div v-else-if="currentQuestion.type === 'FILL_BLANK'">
                   <el-input 
                       v-model="currentAnswer" 
                       placeholder="请输入答案" 
                       @blur="handleAnswerChange" 
                       @change="handleAnswerChange"
                   ></el-input>
                 </div>
                 <el-input 
                    v-else-if="currentQuestion.type === 'SHORT_ANSWER'" 
                    type="textarea" 
                    :rows="5" 
                    v-model="currentAnswer" 
                    placeholder="请输入答案" 
                    @blur="handleAnswerChange"
                 ></el-input>
              </div>
            </div>
            <el-empty v-else description="题目加载中或加载失败..."></el-empty>
          </el-main>

          <el-footer class="exam-footer">
            <!-- 底部按钮区域 -->
            <el-button @click="prevQuestion" :disabled="currentQuestionIndex === 0">上一题</el-button>
            <el-button @click="nextQuestion" :disabled="currentQuestionIndex === totalQuestions - 1">下一题</el-button>
            <el-button type="primary" @click="submitExamHandler">提交试卷</el-button>
          </el-footer>
        </el-container>
      </el-main>
      
      <!-- 右侧答题卡区域 -->
      <el-aside width="250px" class="aside-panel">
        <div class="answer-sheet">
          <h4>答题卡</h4>
          <el-divider />
          <!-- 答题卡按钮 -->
          <div class="sheet-grid">
            <el-button 
              v-for="(q, index) in questions" 
              :key="q.id" 
              :type="getButtonType(index)" 
              size="small" 
              circle 
              class="sheet-button"
              @click="goToQuestion(index)"
            >
              {{ index + 1 }}
            </el-button>
          </div>
        </div>
      </el-aside>
      
    </el-container>
    
    <!-- Loading 遮罩保持不变 -->
    <div v-else class="loading-mask">
        <el-icon class="is-loading" :size="40"><Loading /></el-icon>
        <p>正在加载考试信息...</p>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox, ElContainer, ElHeader, ElMain, ElFooter, ElRadioGroup, ElRadio, ElCheckboxGroup, ElCheckbox, ElInput, ElButton, ElIcon, ElEmpty, ElTag, ElTooltip } from 'element-plus';
import { Loading, WarningFilled } from '@element-plus/icons-vue';
import { startStudentExam, saveAnswer, submitExam, getRemainingTime } from '@/services/examService';
import ExamMonitor from '@/utils/ExamMonitor'; // 假设 ExamMonitor 类放在 utils 目录下

const route = useRoute();
const router = useRouter();

const examId = ref(route.params.id);
const classId = ref(route.query.classId);
const attemptId = ref(null); // 新增：存储考试记录/尝试 ID

const isLoading = ref(true);
const examData = ref(null); // 存储从 startStudentExam 返回的 data 对象
const questions = ref([]);
const currentQuestionIndex = ref(0);
const userAnswers = reactive({}); // 存储用户答案 { questionId: answer }
const remainingTime = ref(0); // 单位：秒
let timerInterval = null;
let syncInterval = null; // 新增：用于存储时间同步定时器 ID
let examMonitor = null;
const SYNC_INTERVAL_MS = 60000; // 时间同步间隔：6秒
const TIME_DIFF_THRESHOLD_S = 5; // 时间差异阈值：5秒

// 新增：存储可疑行为信息
const suspiciousInfo = ref({
  keyboard_shortcut_count: 0,
  copy_paste_count: 0,
  tab_switch_count: 0,
  suspicious_level: 0
});

// --- Computed Properties ---
const totalQuestions = computed(() => questions.value.length);
const currentQuestion = computed(() => questions.value[currentQuestionIndex.value] || null);

// 新增：计算已答题目数量
const answeredQuestionsCount = computed(() => {
  return questions.value.reduce((count, q) => {
    const answer = userAnswers[q.id];
    if (Array.isArray(answer)) { // 多选题
      return answer.length > 0 ? count + 1 : count;
    } else if (answer !== null && answer !== undefined && answer !== '') { // 其他题型 (检查非初始空字符串)
      return count + 1;
    }
    return count;
  }, 0);
});

// 当前题目的答案 (用于 v-model 绑定)
const currentAnswer = computed({
  get() {
    if (!currentQuestion.value) return null;
    const answer = userAnswers[currentQuestion.value.id];
    // 多选题答案应为数组
    if (currentQuestion.value.type === 'MULTIPLE_CHOICE' && !Array.isArray(answer)) {
        return [];
    }
    return answer;
  },
  set(newValue) {
    if (currentQuestion.value) {
      userAnswers[currentQuestion.value.id] = newValue;
      // 注意：这里 set 时不直接调用保存，由 change/blur 或导航时触发
    }
  }
});

const formattedTime = computed(() => {
  if (remainingTime.value <= 0) return '00:00:00';
  const hours = Math.floor(remainingTime.value / 3600);
  const minutes = Math.floor((remainingTime.value % 3600) / 60);
  const seconds = remainingTime.value % 60;
  return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
});

// 新增：计算可疑行为提示 Tag 类型
const suspicionLevelMap = {
  1: { type: 'info', text: '轻微可疑' },
  2: { type: 'warning', text: '较为可疑' },
  3: { type: 'danger', text: '可疑' },
  4: { type: 'danger', text: '高度可疑' },
  5: { type: 'danger', text: '非常可疑' }
};
const suspicionTagType = computed(() => {
  return suspicionLevelMap[suspiciousInfo.value.suspicious_level]?.type || 'info';
});

// 新增：计算可疑行为提示 Tooltip 内容
const suspicionTooltipContent = computed(() => {
  const level = suspiciousInfo.value.suspicious_level;
  const counts = suspiciousInfo.value;
  const baseText = suspicionLevelMap[level]?.text || '未知等级';
  return `${baseText} (快捷键: ${counts.keyboard_shortcut_count}, 复制粘贴: ${counts.copy_paste_count}, 切屏: ${counts.tab_switch_count})`;
});

// --- Methods ---
// 修改 parseOptions 函数，修复选项处理逻辑
const parseOptions = (optionsArray) => {
    if (!Array.isArray(optionsArray)) return [];
    return optionsArray.map((optString, index) => {
        const key = String.fromCharCode(65 + index); // 生成 A, B, C...
        // 只移除真正的选项前缀格式：A. B. C. 等，并且后面必须有空格
        // 修改正则表达式，更加精确地匹配选项前缀
        const value = optString.replace(/^[A-Z]\.(\s+)/, ''); // 只移除 "A. " "B. " 这样的前缀
        return { key: key, value: value.trim() }; 
    });
};

// 获取题目类型文本
const getQuestionTypeText = (type) => {
    const map = {
        SINGLE_CHOICE: '单选',
        MULTIPLE_CHOICE: '多选',
        TRUE_FALSE: '判断',
        FILL_IN_BLANK: '填空',
        SHORT_ANSWER: '简答'
    };
    return map[type] || type;
};

// 启动本地倒计时器
const startTimer = () => {
  if (timerInterval) clearInterval(timerInterval);
  timerInterval = setInterval(() => {
    if (remainingTime.value > 0) {
      remainingTime.value--;
    } else {
      clearInterval(timerInterval);
      // 停止时间同步
      if (syncInterval) clearInterval(syncInterval);
      handleTimeUp();
    }
  }, 1000);
};

// 新增：与服务器同步时间
const syncTimeWithServer = async () => {
  if (!examId.value) return;
  // console.log('[syncTimeWithServer] Attempting to sync time...');
  try {
    const response = await getRemainingTime(examId.value);
    if (response && response.success && response.data !== null) {
      const serverRemainingTime = response.data;
      const localRemainingTime = remainingTime.value;
      const diff = serverRemainingTime - localRemainingTime;
      
      // 如果时间差异超过阈值，则进行校准
      if (Math.abs(diff) > TIME_DIFF_THRESHOLD_S) {
        console.warn(`[syncTimeWithServer] Time difference detected (Server: ${serverRemainingTime}s, Local: ${localRemainingTime}s). Calibrating local timer.`);
        remainingTime.value = serverRemainingTime; // 校准本地时间
      } else {
        // console.log('[syncTimeWithServer] Time is synchronized.');
      }
    } else {
      // 获取失败，打印警告，但不中断本地计时器
      console.warn('[syncTimeWithServer] Failed to get remaining time from server:', response?.message);
    }
  } catch (error) {
    // 异常也静默处理
    console.error('[syncTimeWithServer] Error during time synchronization:', error);
  }
};

// 时间到处理
const handleTimeUp = () => {
  // 确保所有定时器都已停止
  if (timerInterval) clearInterval(timerInterval);
  if (syncInterval) clearInterval(syncInterval);
  ElMessage.warning('考试时间到，系统将自动提交试卷！');
  submitExamHandler(true); // 传入 true 表示自动提交
};

// 处理答案变化（用于自动保存）
const handleAnswerChange = () => {
    if (currentQuestion.value) {
        const questionId = currentQuestion.value.id;
        const answer = userAnswers[questionId];
        // 防抖或节流优化可以加在这里
        saveAnswerHandler(questionId, answer);
    }
};

// 保存答案到后端
const saveAnswerHandler = async (questionId, answer) => {
    if (examId.value && questionId) {
        await saveAnswer(examId.value, questionId, answer);
    }
};

// 导航到上一题
const prevQuestion = () => {
  if (currentQuestionIndex.value > 0) {
    // 导航前保存当前题目答案
    handleAnswerChange(); 
    currentQuestionIndex.value--;
  }
};

// 导航到下一题
const nextQuestion = () => {
  if (currentQuestionIndex.value < totalQuestions.value - 1) {
    // 导航前保存当前题目答案
    handleAnswerChange(); 
    currentQuestionIndex.value++;
  }
};

// 提交试卷处理
const submitExamHandler = async (isAutoSubmit = false) => {
    // 停止计时器和时间同步
    if (timerInterval) clearInterval(timerInterval);
    if (syncInterval) clearInterval(syncInterval);
    
    // 保存最后一题的答案
    await handleAnswerChange(); 

    const confirmAction = async () => {
        isLoading.value = true;
        const monitorData = examMonitor ? examMonitor.getCounts() : {};
        const submissionData = {
            answers: userAnswers,
            ...monitorData
        };
        
        // 添加详细的调试信息
        console.log('=== 考试提交调试信息 ===');
        console.log('监控器是否存在:', !!examMonitor);
        console.log('监控数据:', monitorData);
        console.log('完整提交数据:', submissionData);
        console.log('可疑行为统计:', {
            keyboard_shortcut_count: monitorData.keyboard_shortcut_count || 0,
            copy_paste_count: monitorData.copy_paste_count || 0,
            tab_switch_count: monitorData.tab_switch_count || 0,
            suspicious_level: monitorData.suspicious_level || 0
        });
        console.log('========================');

        try {
            const response = await submitExam(examId.value, submissionData);
            console.log('提交响应:', response);
            if (response && response.success) {
                ElMessage.success(response.message || '试卷提交成功！');
                // 跳转到结果页或列表页
                router.push('/exams'); // 暂时跳回列表
            } else {
                // 提交失败，不恢复计时器，保持按钮可用
                // 错误已在 service 层提示
                console.warn('Manual/Auto submit failed.');
            }
        } catch (error) {
             console.error("Submit exam error:", error);
             // 异常也不恢复计时
        } finally {
            isLoading.value = false;
        }
    };

    if (isAutoSubmit) {
        await confirmAction();
    } else {
        try {
            await ElMessageBox.confirm(
                '确定要提交试卷吗？提交后将无法修改。',
                '确认提交',
                {
                    confirmButtonText: '确定提交',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            );
            await confirmAction();
        } catch (cancel) {
            // 用户取消提交，不恢复计时器，保持原样
            console.log('用户取消提交');
        }
    }
};

// 新增：判断题目是否已作答
const isAnswered = (questionId) => {
  const answer = userAnswers[questionId];
  if (Array.isArray(answer)) { // 多选题
    return answer.length > 0;
  } else { // 其他题型
    return answer !== null && answer !== undefined && answer !== '';
  }
};

// 新增：获取答题卡按钮类型
const getButtonType = (index) => {
  const questionId = questions.value[index]?.id;
  if (!questionId) return ''; // 或者 'info'
  
  const answered = isAnswered(questionId);
  
  if (index === currentQuestionIndex.value) {
      return 'primary'; // 当前题目用 primary
  } else if (answered) {
      return 'success'; // 已答题目用 success
  } else {
      return ''; // 未答题目用默认 type
  }
};

// 新增：跳转到指定题目
const goToQuestion = (index) => {
  if (index >= 0 && index < totalQuestions.value) {
    // 跳转前保存当前答案
    handleAnswerChange(); 
    currentQuestionIndex.value = index;
  }
};

// --- Lifecycle Hooks ---
onMounted(async () => {
  if (!examId.value || !classId.value) {
    ElMessage.error('考试ID或班级ID无效！');
    router.push('/exams');
    return;
  }
  
  isLoading.value = true;
  try {
    const response = await startStudentExam(examId.value, classId.value);

    if (response && response.success && response.data) {
      // 存储整个返回的 data 对象，可能包含 attemptId, examId, etc.
      examData.value = response.data; 
      attemptId.value = response.data.id; // 保存尝试 ID
      
      // 正确获取题目列表
      questions.value = response.data.questions || [];
      
      // 正确获取剩余时间
      remainingTime.value = response.data.remainingTime || 0;
      
      // 解析已保存的答案 (response.data.answers 是 JSON 字符串)
      if (response.data.answers && typeof response.data.answers === 'string') {
        try {
          const savedAnswers = JSON.parse(response.data.answers); // 解析外层 JSON
          if (typeof savedAnswers === 'object' && savedAnswers !== null) {
              // 遍历已保存的答案并更新 userAnswers
              for (const qId in savedAnswers) {
                  let actualAnswer = savedAnswers[qId]; // 可能是原始值，也可能是 '{"answer":...}'
                  
                  // 尝试解析可能存在的内层 JSON (处理双重包装问题)
                  if (typeof actualAnswer === 'string' && actualAnswer.startsWith('{') && actualAnswer.endsWith('}')) {
                      try {
                          const parsedInner = JSON.parse(actualAnswer);
                          // 如果内层解析出来是 { answer: ... } 结构, 取出真实答案
                          if (parsedInner && typeof parsedInner === 'object' && 'answer' in parsedInner) {
                              actualAnswer = parsedInner.answer;
                          }
                      } catch (innerError) {
                          // 解析内层失败，说明它可能就是一个普通的字符串答案（比如填空题或简答题）
                          // 不需要额外处理，保持 actualAnswer 不变
                      }
                  }
                  
                  // 将最终解析出的 actualAnswer 存入 userAnswers
                  userAnswers[qId] = actualAnswer; 
              }
              console.log('已恢复作答记录 (二次解析后):', userAnswers);
          }
        } catch (e) {
          console.error('解析已保存答案失败:', e);
          // 解析失败，不影响继续考试，但之前的答案不会被加载
        }
      }

      // 检查题目是否加载成功
      if (questions.value.length === 0) {
         ElMessage.error('考试题目加载为空，请联系管理员。');
         // 可以选择是否阻止考试进行
         // router.push('/exams');
         // return;
      }
      
      startTimer(); // 启动本地计时器
      
      // 初始化监控器并传入回调
      examMonitor = new ExamMonitor((eventData) => {
          // console.log('[ExamMonitor Callback] Event:', eventData); // 调试用，生产环境可注释
          
          // 更新总的计数值和等级
          suspiciousInfo.value = eventData.counts;
          
          // 根据事件类型弹出即时提示
          let message = '';
          switch (eventData.type) {
              case 'TAB_SWITCH':
                  message = '检测到切屏操作！请专注考试。';
                  break;
              case 'COPY_PASTE':
                  message = '检测到复制粘贴操作！请独立完成。';
                  break;
              case 'KEYBOARD_SHORTCUT':
                  message = `检测到禁用快捷键 (${eventData.key})！`;
                  break;
              default:
                  // 其他未知类型不提示
                  return; 
          }
          ElMessage.warning({ 
              message: message,
              duration: 2000 // 提示显示 2 秒
          });
      });
      // 获取并设置初始监控状态
      suspiciousInfo.value = examMonitor.getCounts();
      
      // 启动时间同步定时器
      if (syncInterval) clearInterval(syncInterval); // 清除旧的（以防万一）
      syncInterval = setInterval(syncTimeWithServer, SYNC_INTERVAL_MS);
      // 立即执行一次同步，以便尽快校准
      syncTimeWithServer(); 

    } else {
      ElMessage.error(response.message || '无法开始考试');
      router.push('/exams');
      return; 
    }
  } catch (error) {
     console.error("Error starting exam:", error);
     ElMessage.error('加载考试时发生错误');
     router.push('/exams');
     return; 
  } finally {
      isLoading.value = false;
  }

});

onUnmounted(() => {
  // 清理所有定时器
  if (timerInterval) {
    clearInterval(timerInterval);
  }
  if (syncInterval) {
    clearInterval(syncInterval);
  }
  if (examMonitor) examMonitor.destroy(); 
});

</script>

<style scoped>
.exam-taking-container {
  height: 100vh;
  display: flex;
}

/* 新增: 主面板和侧边栏样式 */
.main-panel {
  padding: 0; /* 移除 main 的内边距，让内部容器控制 */
  display: flex;
  flex-direction: column; /* 确保内部容器垂直排列 */
}

.aside-panel {
  border-left: 1px solid #e4e7ed;
  background-color: #fcfcfc; /* 侧边栏背景色 */
  padding: 15px;
  display: flex; /* 使内部元素能控制 */
  flex-direction: column;
}

.answer-sheet {
  flex-grow: 1; /* 占据剩余空间 */
  overflow-y: auto; /* 如果题目多，允许滚动 */
}

.answer-sheet h4 {
  text-align: center;
  margin-bottom: 10px;
  color: #303133;
}

.exam-header {
  display: flex;
  justify-content: space-between; /* 改为 space-between */
  align-items: center;
  padding: 0 20px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  height: 60px;
  flex-shrink: 0; /* 防止 header 被压缩 */
}

.header-left {
  flex-shrink: 0; /* 防止标题被压缩 */
}

.header-center {
  /* 中间区域可以留空或放其他东西 */
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px; /* 增加元素间距 */
}

.title {
    font-size: 18px;
    font-weight: bold;
}
.timer {
    color: #f56c6c; 
    font-weight: bold;
}
.progress {
   /* 样式不变 */
}
.suspicion-level {
   /* 样式不变 */
}

.question-area {
  flex-grow: 1; /* 占据主区域剩余空间 */
  padding: 20px;
  overflow-y: auto; /* 内容多时允许滚动 */
}

/* ... question-content, question-stem 等样式不变 ... */

.exam-footer {
  display: flex;
  justify-content: center; /* 按钮居中 */
  align-items: center;
  gap: 20px; /* 按钮间距 */
  padding: 15px 20px;
  background-color: #f5f7fa;
  border-top: 1px solid #e4e7ed;
  height: 60px;
  flex-shrink: 0; /* 防止 footer 被压缩 */
}

/* ... loading-mask 样式不变 ... */

/* 新增: 答题卡网格和按钮样式 */
.sheet-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(40px, 1fr));
  gap: 10px; 
  justify-items: center; /* 新增：让按钮在网格单元内居中 */
}

.sheet-button {
  width: 40px;  
  height: 40px; 
  padding: 0; 
  font-size: 14px;
  margin: 0; /* 新增：确保没有外边距 */
}

/* 可以为不同状态的按钮添加更明显的视觉区分，例如 */
/* .sheet-button.el-button--success {
   background-color: #e1f3d8; 
   border-color: #b3e19d;
   color: #67c23a;
} */

</style> 